"use strict";
var Premium = Premium || {};

/* syncMedia ------------------------------------------------------------------------- */
/**
 * @desc Syncs one media element to another.
 * @param {HTMLMediaElement} mediaMaster The master, controlling video 
 * @param {string} mediaSub The suboridinate, controlled video 
 */
const syncMedia = function(mediaMaster, mediaSub) {
    mediaMaster.addEventListener("playing", function() {
        mediaSub.currentTime = mediaMaster.currentTime;
        mediaSub.play().catch((e) => {});
    })
    mediaMaster.addEventListener("pause", function() {
        mediaSub.pause();
    })
    mediaMaster.addEventListener("volumechange", function() {
        mediaSub.muted = mediaMaster.muted;
        if (!mediaMaster.paused){
            mediaSub.play().catch((e) => {});
            mediaSub.currentTime = mediaMaster.currentTime;
        } 
    })
};
/* syncMedia END --------------------------------------------------------------------- */

/* safariFix ------------------------------------------------------------------------- */
/**
 * @desc Applies the 'Safari fix' to prevent needing to click again to replay the video
 * @param {HTMLVideoElement} [video] - target video
 */
const safariFix = function(video) {
    document.body.addEventListener("click", function(e) {
        if (video.getAttribute("data-media-ended") !== null && e.target.className && (e.target.className.indexOf("jp-controls-play") > -1 || e.target.className.indexOf("jp-controls-replay") > -1 || e.target.className.indexOf("jp-controls-bigplay") > -1)) {
            if (!video.paused) {
                setTimeout(function() {
                    video.play();
                }, 500)
            }
        }
    });
};
/* safariFix END --------------------------------------------------------------------- */

/* pauseWhenOutOfViewWithSync -------------------------------------------------------- */
(function() {
    let targetVideos = [];
    /**
     * @desc Adds pauseWhenOutOfView functionality to a Mobile Skin with synced videos.
     * @param {HTMLMediaElement} video The target video
     * @param {string} videoPlacement Placement of the video(s) top|bottom|both
     */
    window.pauseWhenOutOfViewWithSync = function(video, videoPlacement) {
        targetVideos.push({ video: video, videoPlacement: videoPlacement });
        scrollHandler();
        if (targetVideos.length === 1) {
            Premium.product.scopeWindow.addEventListener("scroll", scrollHandler);
        }
        if (videoPlacement !== "bottom") {
            video.play().catch((e) => {});
        }
        Premium.communicator.api.receiveMessage(function(mess) {
            if (mess.action === "data-outofview") {
                if (mess.set) {
                    video.setAttribute("data-outofview", "");
                } else {
                    video.removeAttribute("data-outofview");
                }
            }
        })
    }
    window.removepauseWhenOutOfViewWithSync = function(video) {
        targetVideos.forEach(function(item, index) {
            if (item.video === video) {
                targetVideos.splice(index, 1);
            }
        });
    }

    var intervalRef, timeoutRef;

    function scrollHandler(e) {
        var percVis = Premium.jpxApi.getPercentageVisibility();
        var rectBottomBar = Premium.product.bottomBarEl().getBoundingClientRect();
        var rectTopBar = Premium.product.topBarEl().getBoundingClientRect();
        var barHeight = Premium.product.topBarEl().clientHeight;
        var panelPos = Premium.jpxApi.getFixedElemPosition();
        targetVideos.forEach(function(item) {
            var lastAction = PremiumJpControls.getLastAction(item.video.parentElement);
            var rectVideo = item.video.getBoundingClientRect();
            if (document.body.id === "body_main") {
                if (percVis.bottom < 50) {
                    if ((rectBottomBar.top - barHeight < rectVideo.bottom - (rectVideo.height / 2)) || (rectTopBar.bottom - barHeight > rectVideo.top + (rectVideo.height / 2))) {
                        if (!item.video.paused) {
                            item.video.pause();
                        }
                        Premium.communicator.api.sendMessage({ action: "data-outofview", set: true })
                    } else {
                        if (item.video.paused && lastAction.playPause !== "pause" &&
                            item.video.getAttribute("data-media-ended") === null) {

                            var prom = item.video.play();
                            if (prom) prom.then(function() {}).catch(function() {});
                        }
                        Premium.communicator.api.sendMessage({ action: "data-outofview", set: false });
                    }
                }
            } else {
                if (percVis.bottom >= 50) {
                    if ((panelPos === item.videoPlacement || item.videoPlacement === "both")) {
                        if (item.video.paused && lastAction.playPause !== "pause" &&
                            item.video.getAttribute("data-media-ended") === null) {
                            var prom = item.video.play();
                            if (prom) prom.catch(() => {});
                        }
                        Premium.communicator.api.sendMessage({ action: "data-outofview", set: false });
                    } else {
                        if (!item.video.paused) {
                            item.video.pause();
                        }
                        Premium.communicator.api.sendMessage({ action: "data-outofview", set: true });
                    }
                }
            }
        })
        if (e && e.target) {
            // continue caling this function after scroll events have stopped
            clearInterval(intervalRef);
            clearTimeout(timeoutRef)
            intervalRef = setInterval(scrollHandler, 20);
            timeoutRef = setTimeout(function() {
                clearInterval(intervalRef);
            }, 500)
        }
    }
})();
/* pauseWhenOutOfViewWithSync END ---------------------------------------------------- */

Premium.creative = {
    init: function() {
        Premium.product.initOrientationMessage();
        /* START OF CUSTOM JS */

        switch (document.body.id) {

            case "body_main":
                // main panel code here
                var videoEl = document.querySelector("VIDEO");
                videoEl.volume = 0;
                Premium.video.sync(videoEl, 2);
                pauseWhenOutOfViewWithSync(videoEl, "both");
                safariFix(videoEl);
                break;

            case "body_bottom":
                // bottom panel code here
                var panelPosition = "top"
                Premium.product.scopeWindow.addEventListener('scroll', function() {
                    if (Premium.jpxApi.getFixedElemPosition() !== panelPosition) {
                        panelPosition = Premium.jpxApi.getFixedElemPosition();
                        Premium.utils.debug(panelPosition);
                        if (panelPosition === "top") {
                            // 'top' instance 
                            gsap.set(".content-top", { visibility: "visible" });
                            gsap.set(".content-bottom", { visibility: "hidden" });
                        } else {
                            // 'bottom' instance
                            gsap.set(".content-top", { visibility: "hidden" });
                            gsap.set(".content-bottom", { visibility: "visible" });
                        }
                    }
                });

                Premium.creative.createVideoPlayerAppended = function(video, container) {

                    // -------------------------------------------------
                    // var audioEl = document.querySelector("AUDIO");
                    // syncMedia(video, audioEl);
                    // Premium.video.initPlayFromUser(video, audioEl);
                    // Premium.product.onBlurChange(function(isHidden){
                    //     audioEl.muted = video.muted;
                    // })
                    // -------------------------------------------------
                    // OR
                    // -------------------------------------------------
                    Premium.video.initPlayFromUser(video);
                    // -------------------------------------------------

                    Premium.video.sync(video, 2);
                    pauseWhenOutOfViewWithSync(video, "both");
                    safariFix(video);

                }
                break;
        }

        /* END OF CUSTOM JS */
    }
};